//index.js
//获取应用实例
var app = getApp()
var Keys = require('../../assets/data/keys')
var CommonUtils = app.CommonUtils

Page({
  data: {
    isCreateOrderFlag: false,  //判断是否点击过购买按钮；防止重复生成订单
    orderType: true, //订单类型， false： 立即支付下单 或  true： 购物车下单，默认立即支付下单，
    addressData: '',
    goodsList: [],
    allGoodsPrice: 0,
    btnBuyNowPay: false,
    realPrice: 0,
    installTypeByOwn: true, //安装方式自己安装
    SizeType: [0, 1],//0:宽  1：高
    datas: [],//要提交服务器的尺寸数据

    index_A: 0,  	//要提交服务器的尺寸数据--第一层
    index_B: 0,		//要提交服务器的尺寸数据--第二层
    index_N: 0,		//要提交服务器的尺寸数据--第三层

    messageText: '',//留言

    maxWidth: 0,  //最大宽度
    maxHeight: 0,	//最大高度

    select: "",
    Money: "",
    PayType: "",
    wMoney: "",//混合支付
    wMoneyHidden: false,//混合支付
  },

  onLoad: function (e) {
    var _this = this;
    _this.setData({
      PayType: "0",
    })
    var tempGoodsList = JSON.parse(e.buyInfo).shopList;
    for (var i = 0, j = tempGoodsList.length; i < j; i++) {
      tempGoodsList[i].SizeArray = new Array(parseInt(tempGoodsList[i].num))
      var SizeArray = [];
      for (var m = 0, n = parseInt(tempGoodsList[i].num); m < n; m++) {
        var size = { "Width": 0, "Height": 0 }
        SizeArray.push(size)
      }
      var tempDatasItem = { 'P_ID': tempGoodsList[i].p_id, 'C_ID': tempGoodsList[i].c_id, "Size": SizeArray };
      this.data.datas.push(tempDatasItem)
    }
    _this.setData({
      goodsList: tempGoodsList,

    })
    _this.requestNetGetOrderSizeRule();
    _this.requestNetGetAddress();
    _this.initOtherData();
  },

  onShow: function () {
    var _this = this;

    _this.setData({
      select: "1"
    })

    try {
      var value = wx.getStorageSync('AddressInfo')
      if (value) {
        _this.setData({
          addressData: JSON.parse(value)
        })
        console.log(value)
        try {
          wx.removeStorageSync('AddressInfo')
        } catch (e) {
        }
      }
    } catch (e) {
    }
    // var num = 0;
    // for (var i = 0; i < _this.data.goodsList.length; i++) {
    // 	num += parseInt(_this.data.goodsList[i].num);
    // }
    // this.setData({
    // 	installTypeByOwn: true,
    // 	realPrice: _this.data.allGoodsPrice - num * 10,
    // })

    console.log("ssss");
    var _this = this;
    console.log(getApp().data.Token),
      wx.request({
        url: 'https://www.chnode.xyz/api/Balance.ashx?',
        data: {
          DataType: "MyBalance",
          Token: getApp().data.Token,
        },
        success: function (res) {
          console.log(res.data.data.U_Blance);
          _this.setData({
            Money: res.data.data.U_Blance,
          })
          console.log(_this.data.realPrice),
            console.log(_this.data.Money)
          var tempMonet = parseFloat(_this.data.realPrice) - parseFloat(_this.data.Money)
          tempMonet = tempMonet.toFixed(2);
          _this.setData({
            wMoney: tempMonet,
          })


          if (parseFloat(_this.data.Money) > 0 && parseFloat(_this.data.wMoney) > 0) {
            _this.setData({
              wMoneyHidden: false,
            })
          } else {
            _this.setData({
              wMoneyHidden: true,
            })
          }
          console.log("vvvvvvvvv");
          console.log(_this.data.wMoneyHidden);
          console.log(_this.data.wMoney);
        }
      })


  },


  /**
   * 初始化其他数据   总价......等
   */
  initOtherData: function () {

    let totalPrice = 0, shopNum = this.data.goodsList.length, num = 0;
    for (let i = 0; i < shopNum; i++) {
      totalPrice = totalPrice + parseFloat(this.data.goodsList[i].num) * parseFloat(this.data.goodsList[i].price)
    }
    for (var i = 0; i < shopNum; i++) {
      num += parseInt(this.data.goodsList[i].num);
    }
    this.setData({
      installTypeByOwn: true,
      allGoodsPrice: totalPrice.toFixed(2),
      realPrice: totalPrice.toFixed(2),
    })
  },

  /**
   * 选择地址
   */
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/W_AddressList/index?IsSelectAddress=" + true
    })
  },

	/**
	 * 点击事件--自己安装
	 */
  btnEventInstallTypeByOwn: function (e) {
    var _this = this;
    var num = 0;
    for (var i = 0; i < _this.data.goodsList.length; i++) {
      num += parseInt(_this.data.goodsList[i].num);
    }
    this.setData({
      installTypeByOwn: true,
      realPrice: _this.data.allGoodsPrice - num * 10,
    })

  },

	/**
	 * 点击事件--服务商安装
	 */
  btnEventInstallTypeByOther: function (e) {
    var _this = this;
    this.setData({
      installTypeByOwn: false,
      realPrice: _this.data.allGoodsPrice,
    })
  },

  btnEventInput: function (e) {
    this.setData({
      index_A: e.currentTarget.dataset.index_a,
      index_B: e.currentTarget.dataset.index_b,
      index_C: e.currentTarget.dataset.index_c,
    })
  },
  bindInputLength: function (e) {
    if (this.data.index_C == 0) {
      this.data.datas[this.data.index_A].Size[this.data.index_B].Height = e.detail.value
    } else if (this.data.index_C == 1) {
      this.data.datas[this.data.index_A].Size[this.data.index_B].Width = e.detail.value
    }
    this.setData({
      datas: this.data.datas
    })
  },

	/**
	 * 监听事件--留言
	 */
  bindInputLiuyan: function (e) {
    this.setData({
      messageText: e.detail.value
    })
  },

	/**
	 * 点击事件--拨打电话
	 */
  btnEventCallPhone: function (e) {
    var _this = this;
    wx.showModal({
      title: '提示',
      content: '是否拨打安装商电话？',
      success: function (res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: _this.data.addressData.SP_Tel //仅为示例，并非真实的电话号码
          })
        }
      }
    })
  },

  btnEventShuoMing: function (e) {
    wx.navigateTo({
      url: '../Fl_GouMai/index?id=https://www.chnode.xyz/web/purchagekonw.html',
    })
  },

  /**
   * 创建订单
   */
  btnEventCreateOrder: function () {
    var _this = this;
    // if (_this.data.isCreateOrderFlag == true) {
    // 	wx.showModal({
    // 		title: '提示',
    // 		content: '订单已生成，请前往订单页查看。',
    // 		showCancel: false,
    // 	})
    // 	return;
    // }
    if (_this.data.addressData == '' || _this.data.addressData == null) {
      CommonUtils.showToastWithImg("请选择地址", 2)
      return;
    }
    for (var i = 0, j = _this.data.datas.length; i < j; i++) {
      for (var m = 0, n = _this.data.datas[i].Size.length; m < n; m++) {
        if (parseFloat(_this.data.datas[i].Size[m].Width) <= 0 || parseFloat(_this.data.datas[i].Size[m].Height) <= 0) {
          CommonUtils.showToastWithImg("请填写尺寸", 2)
          return;
        }
        if (parseFloat(_this.data.datas[i].Size[m].Width) > _this.data.maxWidth) {
          CommonUtils.showToastWithImg("宽度最大为:" + _this.data.maxWidth, 2)
          return;
        }
        if (parseFloat(_this.data.datas[i].Size[m].Height) > _this.data.maxHeight) {
          CommonUtils.showToastWithImg("高度最大为:" + _this.data.maxHeight, 2)
          return;
        }
      }
    }
    _this.reuqestNetOrderByCar();
  },

	/**
	 * 订单尺寸规范
	 */
  requestNetGetOrderSizeRule: function () {
    var _this = this;
    wx.request({
      url: 'https://www.chnode.xyz/api/Order.ashx?DataType=OrderSizeRule',
      success: function (res) {
        if (res.data.isok != 'true')
          return
        _this.data.maxWidth = res.data.data.MaxWidth
        _this.data.maxHeight = res.data.data.MaxLong
        _this.setData({
          maxWidth: _this.data.maxWidth,
          maxHeight: _this.data.maxHeight,
        })
      }
    })
  },

	/**
	 * 网络请求--获取默认地址
	 */
  requestNetGetAddress: function () {
    var _this = this;
    wx.request({
      url: 'https://www.chnode.xyz/api/Address.ashx?DataType=DefaultAddress&Token=' + getApp().data.Token,
      success: function (res) {
        console.log("aaaaaaaaa");
        console.log(res);
        console.log("aaaaaaaaa");
        if (res.data.isok == 'true' && res.data.data != null) {
          _this.setData({
            addressData: res.data.data,
          })
        }
      }
    })
  },

	/**
	 * 网络请求--生成订单
	 */
  reuqestNetOrderByCar: function () {
    var _this = this;
    var tempIsZC = _this.data.installTypeByOwn ? '1' : '0'
    var tempC_ID = ''
    for (var i = 0, j = _this.data.goodsList.length; i < j; i++) {
      tempC_ID = tempC_ID + _this.data.goodsList[i].c_id + ','
    }
    tempC_ID = tempC_ID.substring(0, tempC_ID.length - 1)
    var tempSizeJson = "{'datas':" + JSON.stringify(_this.data.datas) + "}"

    wx.request({

      url: 'https://www.chnode.xyz/api/Order.ashx?DataType=OrderByCar',
      data: {
        A_ID: _this.data.addressData.A_ID,
        O_Note: _this.data.messageText,
        C_ID: tempC_ID,
        Token: getApp().data.Token,
        //SP_ID: _this.data.addressData.SP_ID,
        //IsZC: tempIsZC,
        AS_ID: getApp().data.AS_ID,
        Agent_ID: getApp().data.A_ID,
        SizeJson: tempSizeJson,
      },

      success: function (res) {
        console.log(res)
        if (res.data.isok == "true") {
          console.log("订单生成成功");
          console.log(res.data.data.O_ID);

          if (_this.data.PayType == "0") {
            console.log("微信支付");
            wx.request({
              url: 'https://www.chnode.xyz/api/Pay.ashx?',
              data: {
                DataType: "Wx_Pay",
                PayType: _this.data.PayType,
                O_ID: res.data.data.O_ID,
                Token: getApp().data.Token
              },
              success: function (res) {
                console.log("aaaaaaa");
                console.log(res);
                console.log("aaaaaaa");

                if (res.data.isok == "false") {
                  console.log("请求失败")
                  wx.showModal({
                    title: '提示',
                    content: res.data.info,
                    showCancel: false,
                    success: function (res) {
                      if (res.confirm) {
                        console.log('用户点击确定')
                        wx.navigateBack({
                          delta: 1
                        })
                      } else if (res.cancel) {
                        console.log('用户点击取消')
                      }
                    }
                  })
                } else {
                  console.log("请求成功");
                  wx.requestPayment({
                    timeStamp: res.data.data.timeStamp,
                    nonceStr: res.data.data.nonceStr,
                    "package": res.data.data.package,
                    signType: 'MD5',
                    paySign: res.data.data.paySign,
                    fail: function (aaa) {
                      wx.showModal({
                        title: '提示',
                        content: "订单已经生成",
                        showCancel: false,
                        success: function (res) {
                          if (res.confirm) {
                            console.log('用户点击确定')
                            wx.redirectTo({
                              url: '../W_OrderList/index'
                            });
                          } else if (res.cancel) {
                            console.log('用户点击取消')
                          }
                        }
                      })

                    },
                    success: function () {
                      wx.showToast({ title: '支付成功' })
                      wx.redirectTo({
                        url: '../W_OrderList/index'
                      });
                    }
                  })
                }


              }
            })
          } else if (_this.data.PayType == "1") {
            console.log("微信加于额支付")


            wx.request({
              url: 'https://www.chnode.xyz/api/Pay.ashx?',
              data: {
                DataType: "Wx_Pay",
                PayType: _this.data.PayType,
                O_ID: res.data.data.O_ID,
                Token: getApp().data.Token
              },
              success: function (res) {
                console.log("aaaaaaa");
                console.log(res);
                console.log("aaaaaaa");

                if (res.data.isok == "false") {
                  console.log("请求失败")
                  wx.showModal({
                    title: '提示',
                    content: res.data.info,
                    showCancel: false,
                    success: function (res) {
                      if (res.confirm) {
                        console.log('用户点击确定')
                        wx.navigateBack({
                          delta: 1
                        })
                      } else if (res.cancel) {
                        console.log('用户点击取消')
                      }
                    }
                  })
                } else {

                  console.log("请求成功");
                  wx.requestPayment({
                    timeStamp: res.data.data.timeStamp,
                    nonceStr: res.data.data.nonceStr,
                    "package": res.data.data.package,
                    signType: 'MD5',
                    paySign: res.data.data.paySign,
                    fail: function (aaa) {
                      // wx.showToast({ title: '支付失败:' + aaa })
                      wx.showModal({
                        title: '提示',
                        content: "订单已经生成",
                        showCancel: false,
                        success: function (res) {
                          if (res.confirm) {
                            console.log('用户点击确定')
                            wx.redirectTo({
                              url: '../W_OrderList/index'
                            });
                          } else if (res.cancel) {
                            console.log('用户点击取消')
                          }
                        }
                      })

                    },
                    success: function () {
                      wx.showToast({ title: '支付成功' })
                      wx.redirectTo({
                        url: '../W_OrderList/index'
                      });
                    }
                  })
                }


              }
            })
          } else if (_this.data.PayType == "2") {
            wx.request({
              url: 'https://www.chnode.xyz/api/Pay.ashx?',
              data: {
                DataType: "Wx_Pay",
                PayType: _this.data.PayType,
                O_ID: res.data.data.O_ID,
                Token: getApp().data.Token
              },
              success: function (res) {
                console.log(res);

                wx.showModal({
                  title: '提示',
                  content: res.data.info,
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                      wx.navigateBack({
                        delta: 1
                      })
                    } else if (res.cancel) {
                      console.log('用户点击取消')
                    }
                  }
                })


              }
            })
          }
          console.log(_this.data.PayType)


        } else {
          wx.showModal({
            title: '提示',
            content: res.data.info,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
        // console.log(res.data);
        // wx.showModal({
        // 	title: '提示',
        // 	content: res.data.info,
        // 	showCancel: false,
        // })
        // if (res.data.isok == 'true') {
        // 	_this.data.isCreateOrderFlag = true;
        // }



        // wx.request({
        // 	url: 'https://www.chnode.xyz/api/Pay.ashx?',
        // 	data: {
        // 		DataType: "DemoPay",
        // 		O_ID: res.data.data.O_ID,
        // 	},
        // 	success: function (res) {
        // 		console.log(res);
        // 		if (res.data.isok == "true") {
        // 			wx.showModal({
        // 				title: '提示',
        // 				content: '付款成功',
        // 				showCancel: false,
        // 				success: function (res) {
        // 					if (res.confirm) {
        // 						wx.navigateBack({
        // 							delta: 1,
        // 						})
        // 					} else if (res.cancel) {
        // 						console.log('用户点击取消')
        // 					}
        // 				}
        // 			})
        // 		}
        // 	},
        // })
      },
    })
  },

  // createOrderBuyCar: function (remark) {
  // 	var _this = this;
  // 	if (_this.data.btnBuyNowPay) {
  // 		CommonUtils.showToastWithImg("订单已生成", 2)
  // 		return
  // 	}
  // 	var c_id = "", first_count = "";
  // 	for (var i = 0; i < _this.data.goodsList.length; i++) {
  // 		c_id += _this.data.goodsList[i].car_id + ","
  // 		first_count += _this.data.goodsList[i].num + ","
  // 	}
  // 	wx.request({
  // 		url: Keys.data.url_Order_Add,
  // 		data: {
  // 			DataType: "Order_Add",
  // 			uid: app.login_id,
  // 			haid: _this.data.addressData.HA_ID,
  // 			cid: c_id,
  // 			firstcount: first_count,
  // 			note: remark
  // 		},
  // 		success: function (res) {
  // 			console.log(res)
  // 			if (res.data.isok == "true") {
  // 				_this.setData({
  // 					btnBuyNowPay: true,
  // 				})
  // 				_this.toBuy(res.data.data.HO_ID)
  // 			} else {
  // 				CommonUtils.showToastWithImg(res.data.info, 2)
  // 			}
  // 		}
  // 	})
  // },

  /**
   * 调用微信支付
   */
  toBuy: function (ho_id) {
    console.log(ho_id)
    wx.request({
      url: Keys.data.url_pay,
      data: {
        DataType: "Xcx_WxPay",
        uid: app.login_id,
        openid: app.open_id,
        oid: ho_id
      },
      success: function (res) {
        console.log(res.data)
        wx.requestPayment({
          timeStamp: res.data.data.timeStamp,
          nonceStr: res.data.data.nonceStr,
          "package": res.data.data.package,
          signType: 'MD5',
          paySign: res.data.data.paySign,
          fail: function (aaa) {
            wx.showToast({ title: '支付失败:' + aaa })
          },
          success: function () {
            wx.showToast({ title: '支付成功' })
            wx.redirectTo({
              url: '../order-list/index'
            });
          }
        })
      }
    })
  },

  //余额支付
  one: function () {
    console.log("余额支付");
    var _this = this;
    _this.setData({
      select: "2",
      PayType: "2",
    })
  },

  //微信+余额支付
  two: function () {
    console.log("微信+余额支付")
    var _this = this;
    _this.setData({
      select: "3",
      PayType: "1",
    })
  },

  //微信支付
  three: function () {
    console.log("微信支付")
    var _this = this;
    _this.setData({
      select: "1",
      PayType: "0",
    })
  }
})
